
import 'package:get/get.dart';
import 'package:high_help_apps/common/apis/v1/user.dart';
import 'package:high_help_apps/common/entities/user/user_auth_entity.dart';
import 'package:high_help_apps/common/entities/user/user_login_request_entity.dart';
import 'package:high_help_apps/common/entities/user/user_login_response_entity.dart';
import 'package:high_help_apps/common/routes/app_pages.dart';
import 'package:high_help_apps/common/utils/toast.dart';
import 'package:high_help_apps/common/values/staatus.dart';

import '../../../global.dart';
import 'sign_in_state.dart';

class SignInLogic extends GetxController {

  // 保存一些
  final state = SignInState();

  // TextEditingController usernameController = new TextEditingController();
  // TextEditingController passwordController = new TextEditingController();

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    // usernameController.dispose();
    // passwordController.dispose();
  }

  void redirectToRegisterPage() {
    Get.toNamed(AppRoutes.SIGN_UP);
  }

  void loginAccount(String uname, String passwd) async {
    // 简要验证是否符合登录要求
    if (uname == '' || passwd == '') {
      toastInfo(msg: '信息填写不完整');
      return;
    }
    if (uname.length < 6 || passwd.length < 6) {
      toastInfo(msg: '用户名或密码长度不能小于6位');
      return;
    }

    // 构建出需要传递的数据
    UserLoginRequestEntity params = UserLoginRequestEntity()
        .fromJson({'username': uname, 'password': passwd});

    // 发送请求，执行登录操作
    UserLoginResponseEntity userResponse = await UserAPI.login(params: params);

    // 判断是否登录成功
    if(userResponse.code == STATUS_OK) {

      UserAuthEntity userProfile = UserAuthEntity(
        uid: userResponse.detail!.uid,
        token: userResponse.detail!.token
      );

      Global.saveAuth(userProfile);
      toastInfo(msg: '登录成功!');
      Get.offAllNamed(AppRoutes.HOME_SCAFFOLD);
    } else if(userResponse.code == USER_LOGIN_STATUS_NOT_ACTIVATED) {
      toastInfo(msg: userResponse.message ?? '');
      Get.offAllNamed(AppRoutes.EMAIL_AUTH_PAGE, arguments: {
        'email': userResponse.detail!.email,
        'uid': userResponse.detail!.uid
      });
    } else {
      toastInfo(msg: userResponse.message ?? '登陆失败, 请稍后重试');
    }
  }
}
